<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 4.2.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/myblogs/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/myblogs/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/myblogs/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/myblogs/images/logo.svg" color="#222">

<link rel="stylesheet" href="/myblogs/css/main.css">


<link rel="stylesheet" href="/myblogs/lib/font-awesome/css/font-awesome.min.css">
  <link rel="stylesheet" href="/myblogs/lib/pace/pace-theme-minimal.min.css">
  <script src="/myblogs/lib/pace/pace.min.js"></script>


<script id="hexo-configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    hostname: new URL('http://hackmgod.gitee.io').hostname,
    root: '/myblogs/',
    scheme: 'Gemini',
    version: '7.7.0',
    exturl: false,
    sidebar: {"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},
    copycode: {"enable":false,"show_result":false,"style":null},
    back2top: {"enable":true,"sidebar":false,"scrollpercent":false},
    bookmark: {"enable":false,"color":"#222","save":"auto"},
    fancybox: false,
    mediumzoom: false,
    lazyload: false,
    pangu: false,
    comments: {"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},
    algolia: {
      appID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    },
    localsearch: {"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},
    path: 'search.xml',
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}}
  };
</script>

  <meta name="description" content="观察者模式（Observer模式）详解">
<meta property="og:type" content="article">
<meta property="og:title" content="【31】观察者模式（Observer模式）详解">
<meta property="og:url" content="http://hackmgod.gitee.io/2020/01/17/%E3%80%9031%E3%80%91%E8%A7%82%E5%AF%9F%E8%80%85%E6%A8%A1%E5%BC%8F%EF%BC%88Observer%E6%A8%A1%E5%BC%8F%EF%BC%89%E8%AF%A6%E8%A7%A3/index.html">
<meta property="og:site_name" content="H.m博客">
<meta property="og:description" content="观察者模式（Observer模式）详解">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="http://c.biancheng.net/uploads/allimg/181116/3-1Q1161A6221S.gif">
<meta property="og:image" content="http://c.biancheng.net/uploads/allimg/181116/3-1Q1161A646395.gif">
<meta property="og:image" content="http://c.biancheng.net/uploads/allimg/181116/3-1Q1161AGQ46.gif">
<meta property="og:image" content="http://c.biancheng.net/uploads/allimg/181116/3-1Q1161AP0K8.gif">
<meta property="og:image" content="http://c.biancheng.net/uploads/allimg/181116/3-1Q1161ARKO.gif">
<meta property="article:published_time" content="2020-01-17T05:59:17.000Z">
<meta property="article:modified_time" content="2020-01-17T10:11:00.235Z">
<meta property="article:author" content="H.m">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://c.biancheng.net/uploads/allimg/181116/3-1Q1161A6221S.gif">

<link rel="canonical" href="http://hackmgod.gitee.io/2020/01/17/%E3%80%9031%E3%80%91%E8%A7%82%E5%AF%9F%E8%80%85%E6%A8%A1%E5%BC%8F%EF%BC%88Observer%E6%A8%A1%E5%BC%8F%EF%BC%89%E8%AF%A6%E8%A7%A3/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome: false,
    isPost: true
  };
</script>

  <title>【31】观察者模式（Observer模式）详解 | H.m博客</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

<link rel="alternate" href="/myblogs/atom.xml" title="H.m博客" type="application/atom+xml">
</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-meta">

    <div>
      <a href="/myblogs/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">H.m博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
        <p class="site-subtitle">www.hackm.cn</p>
  </div>

  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>
</div>


<nav class="site-nav">
  
  <ul id="menu" class="menu">
        <li class="menu-item menu-item-home">

    <a href="/myblogs/" rel="section"><i class="fa fa-fw fa-home"></i>首页</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/myblogs/categories/" rel="section"><i class="fa fa-fw fa-th"></i>分类</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/myblogs/archives/" rel="section"><i class="fa fa-fw fa-archive"></i>归档</a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>

</nav>
  <div class="site-search">
    <div class="popup search-popup">
    <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocorrect="off" autocapitalize="none"
           placeholder="搜索..." spellcheck="false"
           type="text" id="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result"></div>

</div>
<div class="search-pop-overlay"></div>

  </div>
</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content">
            

  <div class="posts-expand">
      
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block " lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://hackmgod.gitee.io/2020/01/17/%E3%80%9031%E3%80%91%E8%A7%82%E5%AF%9F%E8%80%85%E6%A8%A1%E5%BC%8F%EF%BC%88Observer%E6%A8%A1%E5%BC%8F%EF%BC%89%E8%AF%A6%E8%A7%A3/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="http://img.hao661.com/zt.hao661.com/uploads/allimg/141006/0644042451-0.jpg">
      <meta itemprop="name" content="H.m">
      <meta itemprop="description" content="欢迎您的到来！">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="H.m博客">
    </span>
      <header class="post-header">
		
        <h1 class="post-title" itemprop="name headline">
          【31】观察者模式（Observer模式）详解
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>
              

              <time title="创建时间：2020-01-17 13:59:17 / 修改时间：18:11:00" itemprop="dateCreated datePublished" datetime="2020-01-17T13:59:17+08:00">2020-01-17</time>
            </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/myblogs/categories/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/" itemprop="url" rel="index">
                    <span itemprop="name">设计模式</span>
                  </a>
                </span>
            </span>

          
            <div class="post-description">观察者模式（Observer模式）详解</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h2 id="【31】观察者模式（Observer模式）详解"><a href="#【31】观察者模式（Observer模式）详解" class="headerlink" title="【31】观察者模式（Observer模式）详解"></a>【31】观察者模式（Observer模式）详解</h2><p>在现实世界中，许多对象并不是独立存在的，其中一个对象的行为发生改变可能会导致一个或者多个其他对象的行为也发生改变。例如，某种商品的物价上涨时会导致部分商家高兴，而消费者伤心；还有，当我们开车到交叉路口时，遇到红灯会停，遇到绿灯会行。这样的例子还有很多，例如，股票价格与股民、微信公众号与微信用户、气象局的天气预报与听众、小偷与警察等。</p>
<p>在软件世界也是这样，例如，Excel 中的数据与折线图、饼状图、柱状图之间的关系；MVC 模式中的模型与视图的关系；事件模型中的事件源与事件处理者。所有这些，如果用观察者模式来实现就非常方便。</p>
<h2 id="模式的定义与特点"><a href="#模式的定义与特点" class="headerlink" title="模式的定义与特点"></a>模式的定义与特点</h2><p>观察者（Observer）模式的定义：指多个对象间存在一对多的依赖关系，当一个对象的状态发生改变时，所有依赖于它的对象都得到通知并被自动更新。这种模式有时又称作发布-订阅模式、模型-视图模式，它是对象行为型模式。</p>
<p>观察者模式是一种对象行为型模式，其主要优点如下。</p>
<ol>
<li>降低了目标与观察者之间的耦合关系，两者之间是抽象耦合关系。</li>
<li>目标与观察者之间建立了一套触发机制。</li>
</ol>
<p>它的主要缺点如下。</p>
<ol>
<li>目标与观察者之间的依赖关系并没有完全解除，而且有可能出现循环引用。</li>
<li>当观察者对象很多时，通知的发布会花费很多时间，影响程序的效率。<h2 id="模式的结构与实现"><a href="#模式的结构与实现" class="headerlink" title="模式的结构与实现"></a>模式的结构与实现</h2>实现观察者模式时要注意具体目标对象和具体观察者对象之间不能直接调用，否则将使两者之间紧密耦合起来，这违反了面向对象的设计原则。<h4 id="1-模式的结构"><a href="#1-模式的结构" class="headerlink" title="1. 模式的结构"></a>1. 模式的结构</h4>观察者模式的主要角色如下。</li>
<li>抽象主题（Subject）角色：也叫抽象目标类，它提供了一个用于保存观察者对象的聚集类和增加、删除观察者对象的方法，以及通知所有观察者的抽象方法。</li>
<li>具体主题（Concrete    Subject）角色：也叫具体目标类，它实现抽象目标中的通知方法，当具体主题的内部状态发生改变时，通知所有注册过的观察者对象。</li>
<li>抽象观察者（Observer）角色：它是一个抽象类或接口，它包含了一个更新自己的抽象方法，当接到具体主题的更改通知时被调用。</li>
<li>具体观察者（Concrete Observer）角色：实现抽象观察者中定义的抽象方法，以便在得到目标的更改通知时更新自身的状态。</li>
</ol>
<p>观察者模式的结构图如图 1 所示。</p>
<p><img src="http://c.biancheng.net/uploads/allimg/181116/3-1Q1161A6221S.gif" alt="观察者模式的结构图"><br>图1 观察者模式的结构图</p>
<h4 id="2-模式的实现"><a href="#2-模式的实现" class="headerlink" title="2. 模式的实现"></a>2. 模式的实现</h4><p>观察者模式的实现代码如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br></pre></td><td class="code"><pre><span class="line">package observer;</span><br><span class="line">import java.util.*;</span><br><span class="line">public class ObserverPattern</span><br><span class="line">&#123;</span><br><span class="line">    public static void main(String[] args)</span><br><span class="line">    &#123;</span><br><span class="line">        Subject subject&#x3D;new ConcreteSubject();</span><br><span class="line">        Observer obs1&#x3D;new ConcreteObserver1();</span><br><span class="line">        Observer obs2&#x3D;new ConcreteObserver2();</span><br><span class="line">        subject.add(obs1);</span><br><span class="line">        subject.add(obs2);</span><br><span class="line">        subject.notifyObserver();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">&#x2F;&#x2F;抽象目标</span><br><span class="line">abstract class Subject</span><br><span class="line">&#123;</span><br><span class="line">    protected List&lt;Observer&gt; observers&#x3D;new ArrayList&lt;Observer&gt;();   </span><br><span class="line">    &#x2F;&#x2F;增加观察者方法</span><br><span class="line">    public void add(Observer observer)</span><br><span class="line">    &#123;</span><br><span class="line">        observers.add(observer);</span><br><span class="line">    &#125;    </span><br><span class="line">    &#x2F;&#x2F;删除观察者方法</span><br><span class="line">    public void remove(Observer observer)</span><br><span class="line">    &#123;</span><br><span class="line">        observers.remove(observer);</span><br><span class="line">    &#125;   </span><br><span class="line">    public abstract void notifyObserver(); &#x2F;&#x2F;通知观察者方法</span><br><span class="line">&#125;</span><br><span class="line">&#x2F;&#x2F;具体目标</span><br><span class="line">class ConcreteSubject extends Subject</span><br><span class="line">&#123;</span><br><span class="line">    public void notifyObserver()</span><br><span class="line">    &#123;</span><br><span class="line">        System.out.println(&quot;具体目标发生改变...&quot;);</span><br><span class="line">        System.out.println(&quot;--------------&quot;);       </span><br><span class="line">       </span><br><span class="line">        for(Object obs:observers)</span><br><span class="line">        &#123;</span><br><span class="line">            ((Observer)obs).response();</span><br><span class="line">        &#125;</span><br><span class="line">       </span><br><span class="line">    &#125;          </span><br><span class="line">&#125;</span><br><span class="line">&#x2F;&#x2F;抽象观察者</span><br><span class="line">interface Observer</span><br><span class="line">&#123;</span><br><span class="line">    void response(); &#x2F;&#x2F;反应</span><br><span class="line">&#125;</span><br><span class="line">&#x2F;&#x2F;具体观察者1</span><br><span class="line">class ConcreteObserver1 implements Observer</span><br><span class="line">&#123;</span><br><span class="line">    public void response()</span><br><span class="line">    &#123;</span><br><span class="line">        System.out.println(&quot;具体观察者1作出反应！&quot;);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">&#x2F;&#x2F;具体观察者1</span><br><span class="line">class ConcreteObserver2 implements Observer</span><br><span class="line">&#123;</span><br><span class="line">    public void response()</span><br><span class="line">    &#123;</span><br><span class="line">        System.out.println(&quot;具体观察者2作出反应！&quot;);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>


<p>程序运行结果如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">具体目标发生改变...</span><br><span class="line"></span><br><span class="line">--------------</span><br><span class="line">具体观察者1作出反应！</span><br><span class="line">具体观察者2作出反应！</span><br></pre></td></tr></table></figure>

<h2 id="模式的应用实例"><a href="#模式的应用实例" class="headerlink" title="模式的应用实例"></a>模式的应用实例</h2><p>【例1】利用观察者模式设计一个程序，分析“人民币汇率”的升值或贬值对进口公司的进口产品成本或出口公司的出口产品收入以及公司的利润率的影响。</p>
<p>分析：当“人民币汇率”升值时，进口公司的进口产品成本降低且利润率提升，出口公司的出口产品收入降低且利润率降低；当“人民币汇率”贬值时，进口公司的进口产品成本提升且利润率降低，出口公司的出口产品收入提升且利润率提升。</p>
<p>这里的汇率（Rate）类是抽象目标类，它包含了保存观察者（Company）的 List 和增加/删除观察者的方法，以及有关汇率改变的抽象方法 change(int number)；而人民币汇率（RMBrate）类是具体目标， 它实现了父类的 change(int number) 方法，即当人民币汇率发生改变时通过相关公司；公司（Company）类是抽象观察者，它定义了一个有关汇率反应的抽象方法 response(int number)；进口公司（ImportCompany）类和出口公司（ExportCompany）类是具体观察者类，它们实现了父类的 response(int number) 方法，即当它们接收到汇率发生改变的通知时作为相应的反应。图 2 所示是其结构图。</p>
<p><img src="http://c.biancheng.net/uploads/allimg/181116/3-1Q1161A646395.gif" alt="人民币汇率分析程序的结构图"><br>图2 人民币汇率分析程序的结构图</p>
<p>程序代码如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br></pre></td><td class="code"><pre><span class="line">package observer;</span><br><span class="line">import java.util.*;</span><br><span class="line">public class RMBrateTest</span><br><span class="line">&#123;</span><br><span class="line">    public static void main(String[] args)</span><br><span class="line">    &#123;</span><br><span class="line">        Rate rate&#x3D;new RMBrate();         </span><br><span class="line">        Company watcher1&#x3D;new ImportCompany(); </span><br><span class="line">        Company watcher2&#x3D;new ExportCompany();           </span><br><span class="line">        rate.add(watcher1); </span><br><span class="line">        rate.add(watcher2);           </span><br><span class="line">        rate.change(10);</span><br><span class="line">        rate.change(-9);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">&#x2F;&#x2F;抽象目标：汇率</span><br><span class="line">abstract class Rate</span><br><span class="line">&#123;</span><br><span class="line">    protected List&lt;Company&gt; companys&#x3D;new ArrayList&lt;Company&gt;();   </span><br><span class="line">    &#x2F;&#x2F;增加观察者方法</span><br><span class="line">    public void add(Company company)</span><br><span class="line">    &#123;</span><br><span class="line">        companys.add(company);</span><br><span class="line">    &#125;    </span><br><span class="line">    &#x2F;&#x2F;删除观察者方法</span><br><span class="line">    public void remove(Company company)</span><br><span class="line">    &#123;</span><br><span class="line">        companys.remove(company);</span><br><span class="line">    &#125;   </span><br><span class="line">    public abstract void change(int number);</span><br><span class="line">&#125;</span><br><span class="line">&#x2F;&#x2F;具体目标：人民币汇率</span><br><span class="line">class RMBrate extends Rate </span><br><span class="line">&#123;</span><br><span class="line">    public void change(int number)</span><br><span class="line">    &#123;       </span><br><span class="line">        for(Company obs:companys)</span><br><span class="line">        &#123;</span><br><span class="line">            ((Company)obs).response(number);</span><br><span class="line">        &#125;       </span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">&#x2F;&#x2F;抽象观察者：公司</span><br><span class="line">interface Company</span><br><span class="line">&#123;</span><br><span class="line">    void response(int number);</span><br><span class="line">&#125;</span><br><span class="line">&#x2F;&#x2F;具体观察者1：进口公司 </span><br><span class="line">class ImportCompany implements Company </span><br><span class="line">&#123;</span><br><span class="line">    public void response(int number) </span><br><span class="line">    &#123;</span><br><span class="line">        if(number&gt;0)</span><br><span class="line">        &#123;</span><br><span class="line">            System.out.println(&quot;人民币汇率升值&quot;+number+&quot;个基点，降低了进口产品成本，提升了进口公司利润率。&quot;); </span><br><span class="line">        &#125;</span><br><span class="line">        else if(number&lt;0)</span><br><span class="line">        &#123;</span><br><span class="line">              System.out.println(&quot;人民币汇率贬值&quot;+(-number)+&quot;个基点，提升了进口产品成本，降低了进口公司利润率。&quot;); </span><br><span class="line">        &#125;</span><br><span class="line">    &#125; </span><br><span class="line">&#125; </span><br><span class="line">&#x2F;&#x2F;具体观察者2：出口公司</span><br><span class="line">class ExportCompany implements Company </span><br><span class="line">&#123;</span><br><span class="line">    public void response(int number) </span><br><span class="line">    &#123;</span><br><span class="line">        if(number&gt;0)</span><br><span class="line">        &#123;</span><br><span class="line">            System.out.println(&quot;人民币汇率升值&quot;+number+&quot;个基点，降低了出口产品收入，降低了出口公司的销售利润率。&quot;); </span><br><span class="line">        &#125;</span><br><span class="line">        else if(number&lt;0)</span><br><span class="line">        &#123;</span><br><span class="line">              System.out.println(&quot;人民币汇率贬值&quot;+(-number)+&quot;个基点，提升了出口产品收入，提升了出口公司的销售利润率。&quot;); </span><br><span class="line">        &#125;</span><br><span class="line">    &#125; </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>


<p>程序运行结果如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">人民币汇率升值10个基点，降低了进口产品成本，提升了进口公司利润率。</span><br><span class="line">人民币汇率升值10个基点，降低了出口产品收入，降低了出口公司的销售利润率。</span><br><span class="line">人民币汇率贬值9个基点，提升了进口产品成本，降低了进口公司利润率。</span><br><span class="line">人民币汇率贬值9个基点，提升了出口产品收入，提升了出口公司的销售利润率。</span><br></pre></td></tr></table></figure>


<p>观察者模式在软件幵发中用得最多的是窗体程序设计中的事件处理，窗体中的所有组件都是“事件源”，也就是目标对象，而事件处理程序类的对象是具体观察者对象。下面以一个学校铃声的事件处理程序为例，介绍 Windows 中的“事件处理模型”的工作原理。</p>
<p>【例2】利用观察者模式设计一个学校铃声的事件处理程序。</p>
<p>分析：在本实例中，学校的“铃”是事件源和目标，“老师”和“学生”是事件监听器和具体观察者，“铃声”是事件类。学生和老师来到学校的教学区，都会注意学校的铃，这叫事件绑定；当上课时间或下课时间到，会触发铃发声，这时会生成“铃声”事件；学生和老师听到铃声会开始上课或下课，这叫事件处理。这个实例非常适合用观察者模式实现，图 3 给出了学校铃声的事件模型。</p>
<p><img src="http://c.biancheng.net/uploads/allimg/181116/3-1Q1161AGQ46.gif" alt="学校铃声的事件模型图"><br>图3 学校铃声的事件模型图</p>
<p>现在用“观察者模式”来实现该事件处理模型。首先，定义一个铃声事件（RingEvent）类，它记录了铃声的类型（上课铃声/下课铃声）；再定义一个学校的铃（BellEventSource）类，它是事件源，是观察者目标类，该类里面包含了监听器容器 listener，可以绑定监听者（学生或老师），并且有产生铃声事件和通知所有监听者的方法；然后，定义一声事件监听者（BellEventListener）类，它是抽象观察者，它包含了铃声事件处理方法 heardBell(RingEvent e)；最后，定义老师类（TeachEventListener）和学生类（StuEventListener），它们是事件监听器，是具体观察者，听到铃声会去上课或下课。图 4 给出了学校铃声事件处理程序的结构。</p>
<p><img src="http://c.biancheng.net/uploads/allimg/181116/3-1Q1161AP0K8.gif" alt="学校铃声事件处理程序的结构图"><br>图4 学校铃声事件处理程序的结构图</p>
<p>程序代码如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br></pre></td><td class="code"><pre><span class="line">package observer;</span><br><span class="line">import java.util.*;</span><br><span class="line">public class BellEventTest</span><br><span class="line">&#123;</span><br><span class="line">    public static void main(String[] args)</span><br><span class="line">    &#123;</span><br><span class="line">        BellEventSource bell&#x3D;new BellEventSource();    &#x2F;&#x2F;铃（事件源）    </span><br><span class="line">        bell.addPersonListener(new TeachEventListener()); &#x2F;&#x2F;注册监听器（老师）</span><br><span class="line">        bell.addPersonListener(new StuEventListener());    &#x2F;&#x2F;注册监听器（学生）</span><br><span class="line">        bell.ring(true);   &#x2F;&#x2F;打上课铃声</span><br><span class="line">        System.out.println(&quot;------------&quot;);   </span><br><span class="line">        bell.ring(false);  &#x2F;&#x2F;打下课铃声</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">&#x2F;&#x2F;铃声事件类：用于封装事件源及一些与事件相关的参数</span><br><span class="line">class RingEvent extends EventObject</span><br><span class="line">&#123;   </span><br><span class="line">    private static final long serialVersionUID&#x3D;1L;</span><br><span class="line">    private boolean sound;    &#x2F;&#x2F;true表示上课铃声,false表示下课铃声</span><br><span class="line">    public RingEvent(Object source,boolean sound)</span><br><span class="line">    &#123;</span><br><span class="line">        super(source);</span><br><span class="line">        this.sound&#x3D;sound;</span><br><span class="line">    &#125;   </span><br><span class="line">    public void setSound(boolean sound)</span><br><span class="line">    &#123;</span><br><span class="line">        this.sound&#x3D;sound;</span><br><span class="line">    &#125;</span><br><span class="line">    public boolean getSound()</span><br><span class="line">    &#123;</span><br><span class="line">        return this.sound;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">&#x2F;&#x2F;目标类：事件源，铃</span><br><span class="line">class BellEventSource</span><br><span class="line">&#123;    </span><br><span class="line">    private List&lt;BellEventListener&gt; listener; &#x2F;&#x2F;监听器容器</span><br><span class="line">    public BellEventSource()</span><br><span class="line">    &#123; </span><br><span class="line">        listener&#x3D;new ArrayList&lt;BellEventListener&gt;();        </span><br><span class="line">    &#125;</span><br><span class="line">    &#x2F;&#x2F;给事件源绑定监听器 </span><br><span class="line">    public void addPersonListener(BellEventListener ren)</span><br><span class="line">    &#123; </span><br><span class="line">        listener.add(ren); </span><br><span class="line">    &#125;</span><br><span class="line">    &#x2F;&#x2F;事件触发器：敲钟，当铃声sound的值发生变化时，触发事件。</span><br><span class="line">    public void ring(boolean sound)</span><br><span class="line">    &#123;</span><br><span class="line">        String type&#x3D;sound?&quot;上课铃&quot;:&quot;下课铃&quot;;</span><br><span class="line">        System.out.println(type+&quot;响！&quot;);</span><br><span class="line">        RingEvent event&#x3D;new RingEvent(this, sound);     </span><br><span class="line">        notifies(event);    &#x2F;&#x2F;通知注册在该事件源上的所有监听器                </span><br><span class="line">    &#125;   </span><br><span class="line">    &#x2F;&#x2F;当事件发生时,通知绑定在该事件源上的所有监听器做出反应（调用事件处理方法）</span><br><span class="line">    protected void notifies(RingEvent e)</span><br><span class="line">    &#123; </span><br><span class="line">        BellEventListener ren&#x3D;null; </span><br><span class="line">        Iterator&lt;BellEventListener&gt; iterator&#x3D;listener.iterator(); </span><br><span class="line">        while(iterator.hasNext())</span><br><span class="line">        &#123; </span><br><span class="line">            ren&#x3D;iterator.next(); </span><br><span class="line">            ren.heardBell(e); </span><br><span class="line">        &#125; </span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">&#x2F;&#x2F;抽象观察者类：铃声事件监听器</span><br><span class="line">interface  BellEventListener extends EventListener</span><br><span class="line">&#123;</span><br><span class="line">    &#x2F;&#x2F;事件处理方法，听到铃声</span><br><span class="line">    public void heardBell(RingEvent e);</span><br><span class="line">&#125;</span><br><span class="line">&#x2F;&#x2F;具体观察者类：老师事件监听器</span><br><span class="line">class TeachEventListener implements BellEventListener</span><br><span class="line">&#123;</span><br><span class="line">    public void heardBell(RingEvent e)</span><br><span class="line">    &#123;        </span><br><span class="line">        if(e.getSound())</span><br><span class="line">        &#123;</span><br><span class="line">            System.out.println(&quot;老师上课了...&quot;);           </span><br><span class="line">        &#125;</span><br><span class="line">        else</span><br><span class="line">        &#123;</span><br><span class="line">            System.out.println(&quot;老师下课了...&quot;);   </span><br><span class="line">        &#125;          </span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">&#x2F;&#x2F;具体观察者类：学生事件监听器</span><br><span class="line">class StuEventListener implements BellEventListener</span><br><span class="line">&#123;</span><br><span class="line">    public void heardBell(RingEvent e)</span><br><span class="line">    &#123;        </span><br><span class="line">        if(e.getSound())</span><br><span class="line">        &#123;</span><br><span class="line">            System.out.println(&quot;同学们，上课了...&quot;);           </span><br><span class="line">        &#125;</span><br><span class="line">        else</span><br><span class="line">        &#123;</span><br><span class="line">            System.out.println(&quot;同学们，下课了...&quot;);   </span><br><span class="line">        &#125;          </span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>


<p>程序运行结果如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">上课铃响！</span><br><span class="line">老师上课了...</span><br><span class="line">同学们，上课了...</span><br><span class="line"></span><br><span class="line">------------</span><br><span class="line">下课铃响！</span><br><span class="line">老师下课了...</span><br><span class="line">同学们，下课了...</span><br></pre></td></tr></table></figure>

<h2 id="模式的应用场景"><a href="#模式的应用场景" class="headerlink" title="模式的应用场景"></a>模式的应用场景</h2><p>通过前面的分析与应用实例可知观察者模式适合以下几种情形。</p>
<ul>
<li>对象间存在一对多关系，一个对象的状态发生改变会影响其他对象。</li>
<li>当一个抽象模型有两个方面，其中一个方面依赖于另一方面时，可将这二者封装在独立的对象中以使它们可以各自独立地改变和复用。<h2 id="模式的扩展"><a href="#模式的扩展" class="headerlink" title="模式的扩展"></a>模式的扩展</h2>在 Java 中，通过 java.util.Observable 类和 java.util.Observer 接口定义了观察者模式，只要实现它们的子类就可以编写观察者模式实例。</li>
</ul>
<ol>
<li>Observable类<br>Observable 类是抽象目标类，它有一个 Vector 向量，用于保存所有要通知的观察者对象，下面来介绍它最重要的 3 个方法。<br>void addObserver(Observer o) 方法：用于将新的观察者对象添加到向量中。<br>void notifyObservers(Object arg) 方法：调用向量中的所有观察者对象的 update。方法，通知它们数据发生改变。通常越晚加入向量的观察者越先得到通知。<br>void setChange() 方法：用来设置一个 boolean 类型的内部标志位，注明目标对象发生了变化。当它为真时，notifyObservers() 才会通知观察者。</li>
<li>Observer 接口<br>Observer 接口是抽象观察者，它监视目标对象的变化，当目标对象发生变化时，观察者得到通知，并调用 void update(Observable o,Object arg) 方法，进行相应的工作。</li>
</ol>
<p>【例3】利用 Observable 类和 Observer 接口实现原油期货的观察者模式实例。</p>
<p>分析：当原油价格上涨时，空方伤心，多方局兴；当油价下跌时，空方局兴，多方伤心。本实例中的抽象目标（Observable)类在 Java 中已经定义，可以直接定义其子类，即原油期货（OilFutures)类，它是具体目标类，该类中定义一个 SetPriCe(float price) 方法，当原油数据发生变化时调用其父类的 notifyObservers(Object arg) 方法来通知所有观察者；另外，本实例中的抽象观察者接口（Observer）在 Java 中已经定义，只要定义其子类，即具体观察者类（包括多方类 Bull 和空方类 Bear），并实现 update(Observable o,Object arg) 方法即可。图 5 所示是其结构图。</p>
<p><img src="http://c.biancheng.net/uploads/allimg/181116/3-1Q1161ARKO.gif" alt="原油期货的观察者模式实例的结构图"><br>图5 原油期货的观察者模式实例的结构图</p>
<p>程序代码如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br></pre></td><td class="code"><pre><span class="line">package observer;</span><br><span class="line">import java.util.Observer;</span><br><span class="line">import java.util.Observable;</span><br><span class="line">public class CrudeOilFutures</span><br><span class="line">&#123;</span><br><span class="line">    public static void main(String[] args)</span><br><span class="line">    &#123;</span><br><span class="line">        OilFutures oil&#x3D;new OilFutures();</span><br><span class="line">        Observer bull&#x3D;new Bull(); &#x2F;&#x2F;多方</span><br><span class="line">        Observer bear&#x3D;new Bear(); &#x2F;&#x2F;空方</span><br><span class="line">        oil.addObserver(bull);</span><br><span class="line">        oil.addObserver(bear);</span><br><span class="line">        oil.setPrice(10);</span><br><span class="line">        oil.setPrice(-8);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">&#x2F;&#x2F;具体目标类：原油期货</span><br><span class="line">class OilFutures extends Observable</span><br><span class="line">&#123;</span><br><span class="line">    private float price;   </span><br><span class="line">    public float getPrice()</span><br><span class="line">    &#123;</span><br><span class="line">        return this.price; </span><br><span class="line">    &#125;</span><br><span class="line">    public void setPrice(float price)</span><br><span class="line">    &#123;</span><br><span class="line">        super.setChanged() ;  &#x2F;&#x2F;设置内部标志位，注明数据发生变化 </span><br><span class="line">        super.notifyObservers(price);    &#x2F;&#x2F;通知观察者价格改变了 </span><br><span class="line">        this.price&#x3D;price ; </span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">&#x2F;&#x2F;具体观察者类：多方</span><br><span class="line">class Bull implements Observer</span><br><span class="line">&#123;   </span><br><span class="line">    public void update(Observable o,Object arg)</span><br><span class="line">    &#123;</span><br><span class="line">        Float price&#x3D;((Float)arg).floatValue();</span><br><span class="line">        if(price&gt;0)</span><br><span class="line">        &#123;</span><br><span class="line">            System.out.println(&quot;油价上涨&quot;+price+&quot;元，多方高兴了！&quot;);</span><br><span class="line">        &#125;</span><br><span class="line">        else</span><br><span class="line">        &#123;</span><br><span class="line">            System.out.println(&quot;油价下跌&quot;+(-price)+&quot;元，多方伤心了！&quot;);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">&#x2F;&#x2F;具体观察者类：空方</span><br><span class="line">class Bear implements Observer</span><br><span class="line">&#123;   </span><br><span class="line">    public void update(Observable o,Object arg)</span><br><span class="line">    &#123;</span><br><span class="line">        Float price&#x3D;((Float)arg).floatValue();</span><br><span class="line">        if(price&gt;0)</span><br><span class="line">        &#123;</span><br><span class="line">            System.out.println(&quot;油价上涨&quot;+price+&quot;元，空方伤心了！&quot;);</span><br><span class="line">        &#125;</span><br><span class="line">        else</span><br><span class="line">        &#123;</span><br><span class="line">            System.out.println(&quot;油价下跌&quot;+(-price)+&quot;元，空方高兴了！&quot;);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>


<p>程序运行结果如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">油价上涨10.0元，空方伤心了！</span><br><span class="line">油价上涨10.0元，多方高兴了！</span><br><span class="line">油价下跌8.0元，空方高兴了！</span><br><span class="line">油价下跌8.0元，多方伤心了！</span><br></pre></td></tr></table></figure>
    </div>

    
    
    

      <footer class="post-footer">

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/myblogs/2020/01/17/%E3%80%9033%E3%80%91%E8%BF%AD%E4%BB%A3%E5%99%A8%E6%A8%A1%E5%BC%8F%EF%BC%88%E8%AF%A6%E8%A7%A3%E7%89%88%EF%BC%89/" rel="prev" title="【33】迭代器模式（详解版）">
      <i class="fa fa-chevron-left"></i> 【33】迭代器模式（详解版）
    </a></div>
      <div class="post-nav-item">
    <a href="/myblogs/2020/01/17/%E3%80%9032%E3%80%91%E4%B8%AD%E4%BB%8B%E8%80%85%E6%A8%A1%E5%BC%8F%EF%BC%88%E8%AF%A6%E8%A7%A3%E7%89%88%EF%BC%89/" rel="next" title="【32】中介者模式（详解版）">
      【32】中介者模式（详解版） <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  

  </div>


          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let activeClass = CONFIG.comments.activeClass;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#【31】观察者模式（Observer模式）详解"><span class="nav-number">1.</span> <span class="nav-text">【31】观察者模式（Observer模式）详解</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#模式的定义与特点"><span class="nav-number">2.</span> <span class="nav-text">模式的定义与特点</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#模式的结构与实现"><span class="nav-number">3.</span> <span class="nav-text">模式的结构与实现</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#1-模式的结构"><span class="nav-number">3.0.1.</span> <span class="nav-text">1. 模式的结构</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-模式的实现"><span class="nav-number">3.0.2.</span> <span class="nav-text">2. 模式的实现</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#模式的应用实例"><span class="nav-number">4.</span> <span class="nav-text">模式的应用实例</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#模式的应用场景"><span class="nav-number">5.</span> <span class="nav-text">模式的应用场景</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#模式的扩展"><span class="nav-number">6.</span> <span class="nav-text">模式的扩展</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="H.m"
      src="http://img.hao661.com/zt.hao661.com/uploads/allimg/141006/0644042451-0.jpg">
  <p class="site-author-name" itemprop="name">H.m</p>
  <div class="site-description" itemprop="description">欢迎您的到来！</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/myblogs/archives/">
        
          <span class="site-state-item-count">42</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/myblogs/categories/">
          
        <span class="site-state-item-count">3</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/hackmgod" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;hackmgod" rel="noopener" target="_blank"><i class="fa fa-fw fa-github"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="/myblogs/hackmgod@foxmail.com" title="E-Mail → hackmgod@foxmail.com"><i class="fa fa-fw fa-envelope"></i>E-Mail</a>
      </span>
      <span class="links-of-author-item">
        <a href="/myblogs/975643993@qq.com" title="QQ → 975643993@qq.com"><i class="fa fa-fw fa-qq"></i>QQ</a>
      </span>
      <span class="links-of-author-item">
        <a href="/myblogs/atom.xml" title="RSS → &#x2F;atom.xml"><i class="fa fa-fw fa-rss"></i>RSS</a>
      </span>
  </div>


  <div class="links-of-blogroll motion-element">
    <div class="links-of-blogroll-title">
      <i class="fa fa-fw fa-link"></i>
      友情链接
    </div>
    <ul class="links-of-blogroll-list">
        <li class="links-of-blogroll-item">
          <a href="https://www.baidu.com/" title="https:&#x2F;&#x2F;www.baidu.com&#x2F;" rel="noopener" target="_blank">百度</a>
        </li>
        <li class="links-of-blogroll-item">
          <a href="https://www.iqiyi.com/" title="https:&#x2F;&#x2F;www.iqiyi.com&#x2F;" rel="noopener" target="_blank">爱奇艺</a>
        </li>
    </ul>
  </div>

      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        <!-- 用下面的符号注释，注释代码用下面括号括起来 -->
<!-- -->

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">H.m</span>
</div>


<!--
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> 强力驱动 v4.2.0
  </div>
  <span class="post-meta-divider">|</span>
  <div class="theme-info">主题 – <a href="https://theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Gemini</a> v7.7.0
  </div> -->

<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

<div class="powered-by">
  <i class="fa fa-user-md"></i>
  <span id="busuanzi_container_site_pv">
    本站访问量:<span id="busuanzi_value_site_pv"></span>次
  </span>
  <span class="post-meta-divider">|</span>
  <span id="busuanzi_container_site_uv">
    本站总访客量：<span id="busuanzi_value_site_uv"></span>人
  </span>
</div>





        








      </div>
    </footer>
  </div>

  
  <script src="/myblogs/lib/anime.min.js"></script>
  <script src="/myblogs/lib/velocity/velocity.min.js"></script>
  <script src="/myblogs/lib/velocity/velocity.ui.min.js"></script>

<script src="/myblogs/js/utils.js"></script>

<script src="/myblogs/js/motion.js"></script>


<script src="/myblogs/js/schemes/pisces.js"></script>


<script src="/myblogs/js/next-boot.js"></script>




  




  
<script src="/myblogs/js/local-search.js"></script>













  

  

</body>
</html>


<a href="https://github.com/hackmgod" target="_blank" rel="noopener" class="github-corner" aria-label="View source on GitHub"><svg width="80" height="80" viewBox="0 0 250 250" style="fill:#151513; color:#fff; position: absolute; top: 0; border: 0; right: 0;" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a><style>.github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}</style>


<!-- 动态背景 -->
<script type="text/javascript" src="//cdn.bootcss.com/canvas-nest.js/1.0.0/canvas-nest.min.js"></script>
<!-- 页面点击小红心 -->
<script type="text/javascript" src="/js/src/clicklove.js"></script>